import Vuex, {ActionObject, ActionMethod, Module} from "vuex";
import {
  getToken,
  setToken,
  removeToken,
  setUserInfo,
  getUserInfo,
  removeUserInfo,
} from "@/utils/auth";
import $api from "@/api/index";
import router from "@/router";
import * as mt from "./mutations-types";

export default {
  namespaced: true,
  state: {
    token: "",
    info: {
      avatar: '',
      name: ''
    },
  },
  mutations: {
    [mt.SET_TOKEN](state, data) {
      state.token = data;
    },
    [mt.SET_USER_INFO](state, userData = {}) {
      state.info = userData;
    },
    [mt.CLEAR_USER_INFO](state) {
      state.info = {};
      state.token = null;
    },
  },
  actions: {
    login({commit}, data) {
      return new Promise((resolve, reject) => {
        $api.user.login(data).then(result => {
          commit(mt.SET_TOKEN, result.data.token);
          commit(mt.SET_USER_INFO, result.data);
          setToken(result.data.token);
          setUserInfo(result.data);
          resolve(result)
        }).catch(error => {
          reject(error)
        })
      })

    },
    info({commit}) {
      let userInfo = getUserInfo()
      commit(mt.SET_USER_INFO, userInfo);
      // 用户信息每次进入都重新获取到session
      // setUserInfo(result.data);
    },
    logout({commit}) {
      commit(mt.CLEAR_USER_INFO);
      removeToken();
      removeUserInfo();
    },
    checkPay({commit}) {
      let userInfo = getUserInfo()
      commit(mt.SET_USER_INFO, userInfo);
      // 用户信息每次进入都重新获取到session
      // setUserInfo(result.data);
    },
    //根据身份 判断是否重新登录
    checkRole({commit}, type) {
      return new Promise((resolve, reject)=>{
        let userInfo = getUserInfo()
        if (userInfo.type !== type) {
          if (type === '3') {
            router.push('/login_dl')
          } else if(type==='2') {
            router.push('/Login')
          }
          commit(mt.CLEAR_USER_INFO);
          removeToken();
          removeUserInfo();
          reject()
        }else{
          resolve()
        }
      })

    },
  },
  getters: {
    token(state) {
      return state.token;
    },
    info(state) {
      return state.info;
    },
  },
};
